package org.lex.awt;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Point;

import javax.swing.SwingConstants;

public class Location implements SwingConstants {
	private Location() {
	}

	public static Point getScreenCenterPoint() {
		return GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
	}

	public static void moveToParentLeft(Component parent, Component child) {
		Point loc = parent.getLocationOnScreen();
		loc.x += parent.getWidth();
		loc.y += (parent.getHeight() - child.getHeight()) / 2;
		child.setLocation(loc);
	}

	public static void moveToParentCenter(Component parent, Component child) {
		Point loc = parent.getLocationOnScreen();
		child.setLocation(loc.x + (parent.getWidth() - child.getWidth()) / 2, loc.y + (parent.getHeight() - child.getHeight()) / 2);
	}

	public static void moveToScreenCenter(Component c) {
		Point center = Location.getScreenCenterPoint();
		c.setLocation(center.x - c.getWidth() / 2, center.y - c.getHeight() / 2);
	}

	public static void moveToParent(Component parent, Component child, int position) {
		Point pl = parent.getLocationOnScreen(); // parent location
		Dimension ps = parent.getSize(); // parent size
		Dimension cs = child.getSize(); // child size
		switch (position) {
		case SwingConstants.SOUTH_EAST:
			child.setLocation(pl.x + ps.width - cs.width, pl.y + ps.height - cs.height);
			break;
		default:
			moveTo(child, SwingConstants.SOUTH_WEST);
			break;
		}
	}

	public static void moveTo(Component c, int position) {
		Location.move(c, Location.getScreenCenterPoint(), position);
	}

	private static void move(Component c, Point center, int position) {
		int width = c.getWidth();
		int height = c.getHeight();
		int x = 0, y = 0;
		switch (position) {
		case SwingConstants.CENTER:
			x = center.x - width / 2;
			y = center.y - height / 2;
			break;
		case SwingConstants.NORTH:
			x = center.x - width / 2;
			y = 0;
			break;
		case SwingConstants.NORTH_WEST:
			x = 0;
			y = 0;
			break;
		case SwingConstants.WEST:
			x = 0;
			y = center.y - height / 2;
			break;
		case SwingConstants.SOUTH_WEST:
			x = 0;
			y = center.y * 2 - height;
			break;
		case SwingConstants.SOUTH:
			x = center.x - width / 2;
			y = center.y * 2 - height;
			break;
		case SwingConstants.SOUTH_EAST:
			x = center.x * 2 - width;
			y = center.y * 2 - height;
			break;
		case SwingConstants.EAST:
			x = center.x * 2 - width;
			y = center.y - height / 2;
			break;
		case SwingConstants.NORTH_EAST:
			x = center.x * 2 - width;
			y = 0;
			break;
		default:
			throw new IllegalArgumentException("[" + position + "] isn't valid, SwingConstants expected.");
		}
		x = x < 0 ? 0 : x;
		y = y < 0 ? 0 : y;
		c.setLocation(x, y);
	}
}
